package com.magicode.screen.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpInternet {
	 public static byte[] getByte(String path) throws Exception{
		 String userid="";
		 if(null!=path && path.contains("?")){
		   	path=path.replace("?", ",");
		   	path = path.split(",")[0];
			String path_2 = path.split(",")[1];
			userid =path_2.split("=")[1];
		}
       HttpClient httpclient = new DefaultHttpClient();
       HttpGet get = new HttpGet(path);
       
       get.setHeader("androidtoken", userid);
       HttpResponse response = httpclient.execute(get );
       int code = response.getStatusLine().getStatusCode(); 
       if(code==200){
    	   InputStream inStream = response.getEntity().getContent();
      	 	ByteArrayOutputStream outStream = new ByteArrayOutputStream();
           byte[] buffer = new byte[1024];
           int len = 0;
           while( (len=inStream.read(buffer)) != -1){
               outStream.write(buffer, 0, len);
           }
           outStream.close();
           inStream.close();
           return outStream.toByteArray();
       }
       return null;
	}
	 /**
	  * 根据链接地址得到文件流
	  * @param path
	  * @return
	  * @throws Exception
	  */
	 public static InputStream getInputStream(String url) throws Exception{
		
       HttpClient httpclient = new DefaultHttpClient();
       HttpGet get = new HttpGet(url);
       
       HttpResponse response = httpclient.execute(get );
       int code = response.getStatusLine().getStatusCode(); 
       if(code==200){
    	   InputStream inStream = response.getEntity().getContent();
      	 
           return inStream;
       }
       return null;
	}
	public  static void sendHttpDelete(String path,String userid)  throws Exception{
		HttpDelete delete = new HttpDelete(path);
		delete.setHeader("androidtoken", userid);
		new DefaultHttpClient().execute(delete);
	}
	
	/**
	 * POST application/json
	 * @param path
	 * @param body
	 * @return
	 * @throws Exception
	 */
	public static String  sendHttpClientByJson(String path,String body,String method)throws Exception{
		return sendHttpClientByJson(path,body,method,true);
	}
	
	public static String  sendHttpClientByJson(String path,String body,String method,boolean result)throws Exception{
		String bodystr = (null==body||"".equals(body))?"":body;
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		String method_ = conn.getRequestMethod();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod(method);
		method_ = conn.getRequestMethod();
		if("POST".equals(method)){   
			//输出数据权限
			conn.setDoOutput(true);
			conn.setDoInput(true);
		}
		else if("GET".equals(method)){
			//conn.setRequestProperty("Content-Type", "text/xml");
		}
		if(null!=bodystr &&!"".equals(bodystr)){
			byte[] prams = bodystr.getBytes();
			conn.getOutputStream().write(prams);
			conn.getOutputStream().flush();  
			conn.getOutputStream().close(); 
		}
		conn.connect(); 
		try {
			if(conn.getResponseCode()==200&&result){
				return getRequestReturn(conn);
			}
			else{
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * return by request  response data
	 * @param conn
	 * @return
	 */
	public static String getRequestReturn( URLConnection urlConnection)throws Exception{
	  InputStream in = 	urlConnection.getInputStream();
      BufferedReader rd = new BufferedReader(new InputStreamReader(in));
      String tempLine = rd.readLine();
      StringBuffer temp = new StringBuffer();

      while (tempLine != null)
      {                
    	  temp.append(tempLine);
          tempLine = rd.readLine();
      }
      String tempStr = new String( temp.toString().getBytes(),"utf-8");
      String responseContent = temp.toString();
      rd.close();
      in.close();
      return responseContent;
	
	}
	/**
	 * 通过Post方法得到json数据
	 * 使用UTF-8编码
	 * @param path
	 * @return
	 * @throws Exception
	 */
	 public static String getJsonByPost(String path) throws Exception{
		 String result = null;
		String contentType =  "text/xml";
      HttpClient httpclient = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost(path);
//      StringEntity entity = new StringEntity("","UTF-8");
//      entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, contentType));
//      httpPost.getParams()
//      httpPost.setHeader(header);;
      HttpResponse response = httpclient.execute(httpPost );
//      response.setEntity(entity);
//      response.se("UTF-8");
      int code = response.getStatusLine().getStatusCode(); 
      if(code==200){
   	   InputStream inStream = response.getEntity().getContent();
//     	 	ByteArrayOutputStream outStream = new ByteArrayOutputStream();
     	 	BufferedReader br = new BufferedReader(new InputStreamReader(inStream,"utf-8"));
     	 	StringBuffer sbf = new StringBuffer();
     	 	String line = null;
     	 	while ((line = br.readLine()) != null)
     	 	{
     	 	sbf.append(line);
     	 	}
     	 	result = sbf.toString();
     	 	br.close();
//          byte[] buffer = new byte[1024];
//          int len = 0;
//          while( (len=inStream.read(buffer)) != -1){
//              outStream.write(buffer, 0, len);
//          }
//          outStream.close();
//          inStream.close();
//          return new String(outStream.toByteArray());
      }
      return result;
	}
 /**
	 * 通过Post方法得到json数据
	 * 使用UTF-8编码
	 * @param path
	 * @return
	 * @throws Exception
	 */
	 public static String getJsonByGet(String path) throws Exception{
		 String result = null;
//		 java.awt.image.ConvolveOp
		String contentType =  "text/xml";
      HttpClient httpclient = new DefaultHttpClient();
      HttpGet httpPost = new HttpGet(path);
//	      StringEntity entity = new StringEntity("","UTF-8");
//	      entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, contentType));
//	      httpPost.getParams()
//	      httpPost.setHeader(header);;
      HttpResponse response = httpclient.execute(httpPost );
//	      response.setEntity(entity);
//	      response.se("UTF-8");
      int code = response.getStatusLine().getStatusCode(); 
      if(code==200){
   	   InputStream inStream = response.getEntity().getContent();
//	     	 	ByteArrayOutputStream outStream = new ByteArrayOutputStream();
     	 	BufferedReader br = new BufferedReader(new InputStreamReader(inStream,"UTF-8"));
//     	 	BufferedReader br = new BufferedReader(new InputStreamReader(inStream));
     	 	StringBuffer sbf = new StringBuffer();
     	 	String line = null;
     	 	while ((line = br.readLine()) != null)
     	 	{
     	 	sbf.append(line).append("\n");
     	 	}
     	 	result = sbf.toString();
     	 	br.close();
      }

//		result = new String(result.getBytes("ISO-8859-1"),"UTF-8");
      return result;
	}
	 

}
